package rdw.ui;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.SystemTray;
import java.awt.PopupMenu;
import java.awt.TrayIcon;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

/**
 * SystrayIcon manages the systray icon and interaction between the user 
 * interface (on the host) and the main RDWApp class.
 */
public class SystrayIcon
{
	private SystemTray systray;
	private TrayIcon trayIcon;
	private PopupMenu menu;
	private MenuCallback callback;
	
	public SystrayIcon(final MenuCallback callback)
	{
		this.callback = callback;
		
		if (!SystemTray.isSupported())
		{
			AlertDialog.showAlert("Remote Desktop Web", "System Tray Icon unavailable on operating system. Unable to start.");
			throw new RuntimeException();
		}
		
		systray = SystemTray.getSystemTray();
		
		menu = new PopupMenu();
		
		menu.add("RDW: Remote Desktop Web Running...");
		
		// add "Set Port" menu item
		MenuItem portItem = new MenuItem("Set Port");
		portItem.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0)
			{
				showPortDialog(callback.getPort());
			}
		});
		menu.add(portItem);
		
		// add "Shutdown" menu item
		MenuItem shutdownItem = new MenuItem("Shutdown RDW");
		shutdownItem.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0)
			{
				System.exit(0);
				
			}
		});
		menu.add(shutdownItem);

		// add "About" menu item
		MenuItem aboutItem = new MenuItem("About...");
		aboutItem.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0)
			{
				showAboutDialog(callback.getPort());
				
			}
		});
		menu.add(aboutItem);
		
		Image image = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/icons/icon.png"));
		trayIcon = new TrayIcon(image);
		trayIcon.setImageAutoSize(true);
		trayIcon.setPopupMenu(menu);
		trayIcon.setToolTip("Remote Desktop Web");
		
		try
		{
			systray.add(trayIcon);
		}
		catch (AWTException e)
		{
			// this exception should never happen.
			e.printStackTrace();
		}
	}
	
	private void showPortDialog(int currentPort)
	{
		String newPort = JOptionPane.showInputDialog("Enter TCP Port", Integer.toString(currentPort));
		if (newPort != null && !newPort.equals(""))
		{
			callback.changePort(Integer.parseInt(newPort));
		}
	}
	
	private void showAboutDialog(int currentPort)
	{
		String content = "Remote Desktop Web, Beta version 0.1\n" +
			"(c) 2008, Brett A. Taylor (brett@realbt.com)\n" +
			"http://rdw.googlecode.com/\n\n" +
			this.callback.getBoundIps() + "\n" +
			"Running on TCP port " + Integer.toString(currentPort);
		JOptionPane.showMessageDialog(null, content, "About Remote Desktop Web", JOptionPane.INFORMATION_MESSAGE);
	}
}
